export default {
    namespaced: true,
    state: {
        productions: JSON.parse(window.localStorage.getItem('cart-productions')) || [],
    },
    mutations: {
        addCart(state, payload) {
            const production = state.productions.find(prod => prod.id === payload.id)
            if (production) {
                production.count++;
                production.totalPrice += production.price
            } else {
                state.productions.push({
                    id: payload.id,
                    price: payload.price,
                    title: payload.title,
                    totalPrice: payload.price * 1,
                    count: 1,
                    isChecked: true
                })
            }
        },
        removeCart(state, payload) {
            const index = state.productions.findIndex(prod => prod.id === payload.id)
            if (index > -1) state.productions.splice(index, 1)
        },
        changeChecked(state, payload) {
            const production = state.productions.find(prod => prod.id === payload.id)
            if (!production) return;
            production.isChecked = payload.checked;
        }
    },
    getters: {
        totalPrice: (state) => {
            let totalPrice = 0;
            state.productions.forEach((production) => {
                totalPrice += production.price * production.count
            })
            return totalPrice;
        },
        totalCount: (state) => {
            let totalCount = 0;
            state.productions.forEach((production) => {
                totalCount += production.count
            })
            return totalCount;
        },
        isCheckedTotalPrice: (state) => {
            let totalPrice = 0;
            state.productions.forEach((production) => {
                if (!production.isChecked) return;
                totalPrice += production.price * production.count
            })
            return totalPrice;
        },
        isCheckedTotalCount: (state) => {
            let totalCount = 0;
            state.productions.forEach((production) => {
                if (!production.isChecked) return;
                totalCount += production.count
            })
            return totalCount;
        }
    },
    actions: {},
}